package cn.huugh.number;

import cn.huugh.number.cn.hugh.netutil.ConnectedSocket;
import cn.huugh.number.cn.hugh.netutil.DataSource;
import cn.huugh.number.cn.hugh.netutil.MessageHandler;
import cn.huugh.number.cn.hugh.netutil.SocketEvent;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@SpringBootApplication
public class NumberApplication {
    public static ApplicationContext context;
    public static final ExecutorService SERVICE = Executors.newSingleThreadExecutor();
    public static List<ConnectedSocket> modelList = new LinkedList<>();
    public static List<DataSource> dataSources = new ArrayList<>();
    public static void main(String[] args) {
        context = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        SpringApplication.run(NumberApplication.class, args);
        try {
            ServerSocket serverSocket = new ServerSocket(14159); // 以后要是做分布式pytorch模型可以用得上！
            SERVICE.execute(()->{
                while(true){
                    try {
                        ConnectedSocket cs = new ConnectedSocket(serverSocket.accept(), new MessageHandler() {
                            @Override
                            public void onClientConnected(SocketEvent e){
                                System.out.println(e.getConnectedSocket().getSocket().getInetAddress()+"连接了服务器");
                            }
                            @Override
                            public void onMessageReceive(SocketEvent e, String message) {
                                if(!(message+"").equals("null")){
                                    if (dataSources.size()!=0) {
                                        dataSources.get(0).data = message;
                                        //System.out.println(dataSources.get(0).data);
                                    }
                                    //dataSources.remove(0); // 队列
                                }
                            }
                            @Override
                            public void onClientDisconnected(SocketEvent e){
                                System.out.println(e.getConnectedSocket().getSocket().getInetAddress()+"与服务器连接断开");
                                modelList.remove(e.getConnectedSocket());
                            }
                        });
                        modelList.add(cs);
                    } catch (IOException ignored) { }
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }


    }


}